package elcom.model.data;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import elcom.model.common.Log;
import elcom.model.connection.DBConnection;

public class Student {

	private Connection con = DBConnection.getConnection();
	private Integer studentID;
	private String firstName;
	private String lastName;
	private BigDecimal math;
	private BigDecimal phys;
	private BigDecimal chem;

	public Student(Integer studentID) {
		this.studentID = studentID;
		String sql = "select * from p_student where p_student_id = ?";
		if (con == null) {
			firstName = "";
			lastName = "";
			math = BigDecimal.ZERO;
			phys = BigDecimal.ZERO;
			chem = BigDecimal.ZERO;
		} else {
			PreparedStatement ps = null;
			ResultSet rs = null;
			try {
				ps = con.prepareStatement(sql);
				ps.setInt(1, studentID);
				rs = ps.executeQuery();
				if (rs.next()) {
					firstName = rs.getString("firstName");
					lastName = rs.getString("lastName");
					math = rs.getBigDecimal("Math");
					phys = rs.getBigDecimal("Phys");
					chem = rs.getBigDecimal("Chem");
				} else {
					firstName = "";
					lastName = "";
					math = BigDecimal.ZERO;
					phys = BigDecimal.ZERO;
					chem = BigDecimal.ZERO;
				}
			} catch (Exception e) {
				e.printStackTrace();
				Log.logErr(e.toString());
			} finally {
				try {
					if (rs != null) {
						rs.close();
					}
					if (ps != null) {
						ps.close();
					}
				} catch (Exception e) {
					e.printStackTrace();
					Log.logErr(e.toString());
				}
			}

		}
	}

	@Override
	public String toString() {
		StringBuffer value = new StringBuffer();
		value.append(studentID).append("___");
		value.append(firstName).append("-");
		value.append(lastName).append("___");
		value.append(math.add(phys).add(chem));
		return value.toString();
	}

	public int getStudentID() {
		return studentID;
	}

	protected void updateIsUsed() {
		String sql = "update p_student set isused = 'Y' where p_student_id = ? ";
		Connection con = DBConnection.getConnection();
		PreparedStatement ps = null;
		try {
			ps = con.prepareStatement(sql);
			ps.setInt(1, studentID);
			ps.executeUpdate();
			con.commit();
		} catch (Exception e) {
			e.printStackTrace();
			Log.logErr(e.toString());
			System.exit(0);
		} finally {
			try {
				if (ps != null) {
					ps.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
				Log.logErr(e.toString());
			}

		}
	}

}
